<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
	<meta http-equiv="Cache-Control" content="no-siteapp" />
	<meta name="viewport"
		content="width=device-width, maximum-scale=1.0, initial-scale=1.0,initial-scale=1.0,user-scalable=no" />
	<meta name="apple-mobile-web-app-capable" content="yes" />
    <title><#if inviteData?? && inviteData.aititle??>${inviteData.aititle}<#else>智能客服</#if></title>

	<link rel="shortcut icon" type="image/x-icon"
		  href="<#if systemConfig?? && systemConfig.favlogo?? && systemConfig.favlogo != ''>/res/image.html?id=${systemConfig.favlogo?url}<#else>/images/favicon.ico?v=ukefu</#if>&t=${.now?long}" />
    <link rel="stylesheet" type="text/css" href="/im/css/ukefu.css">
    <link rel="stylesheet" id="skin" type="text/css" href="/im/css/default/ukefu.css">
    
    <!-- kindeditor -->
    <link rel="stylesheet" type="text/css" href="/im/js/kindeditor/themes/default/default.css">
    
    <script type="text/javascript" src="/js/jquery-1.10.2.min.js"></script>
    <script src="/js/jquery.form.js"></script>
    
    <script type="text/javascript" src="/im/js/kindeditor/kindeditor.js"></script>
    <script type="text/javascript" src="/im/js/kindeditor/lang/zh-CN.js"></script>
    <script src="/js/recordmp3.js"></script>
    <#if inviteData?? && inviteData.enablevoice?? && inviteData.enablevoice == true>
    <script src="/js/ukefu-voice.js"></script>
    </#if>
    <script src="/js/weixinAudio.js"></script>
    <script src="/js/template.js"></script>
    <style>
    	* {
			-webkit-box-sizing: border-box;
			-moz-box-sizing: border-box;
			box-sizing: border-box;
			-webkit-tap-highlight-color: transparent;
			outline: none;
		}
		*:not(input,textarea) { 
			-webkit-touch-callout: none; 
		  -webkit-user-select: none; 
		}
		.ukefu-suggest{
			position: fixed;
		    width: 100%;
		    bottom: 0px;
		    margin-bottom: 55px;
		    border: 1px solid #dedede;
		    border-left:0px;
		    border-right:0px;
		    background-color: #ffffff;
		    padding: 0px 5px 0 0px;
		    line-height: 25px;
		    font-size: 16px;
		    display:none;
		    z-index:1000;
		    -webkit-transform: translateZ(0);
		}
		.ukefu-suggest a{
			color:#333333;
			text-decoration: none;
		}
		.ukefu-suggest-change{
			position: absolute;
		    right: 0px;
		    padding: 0px 5px;
		    color: #4665d4;
		}
    </style>
    
    <script src="/im/js/socket.io.js"></script>
    <script type="text/javascript">
   
    var editor , words , textheight , wordinx = 0 ,callback , schema = '${schema!"http"}' ,agent = false , invite = false  , upload = "/im/voice/upload.html?userid=${userid!''}&appid=${appid!''}&orgi=${orgi!''}";
    var options = {
			transports:[
				<#if inviteData?? && inviteData.transports?? && inviteData.transports =="websocket">
				'websocket'
				<#elseif inviteData?? && inviteData.transports?? && inviteData.transports =="polling" >
				'polling'
				<#else>
				'websocket','polling'
				</#if>
			]
	} ;
    /**
     * 文本框根据输入内容自适应高度
     * @param                {HTMLElement}        输入框元素
     * @param                {Number}                设置光标与输入框保持的距离(默认0)
     * @param                {Number}                设置最大高度(可选)
     */
    var autoTextarea = function (elem, extra, maxHeight) {
            extra = extra || 0;
            var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
            isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
                    addEvent = function (type, callback) {
                            elem.addEventListener ?
                                    elem.addEventListener(type, callback, false) :
                                    elem.attachEvent('on' + type, callback);
                    },
                    getStyle = elem.currentStyle ? function (name) {
                            var val = elem.currentStyle[name];
                            
                            if (name === 'height' && val.search(/px/i) !== 1) {
                                    var rect = elem.getBoundingClientRect();
                                    return rect.bottom - rect.top -
                                            parseFloat(getStyle('paddingTop')) -
                                            parseFloat(getStyle('paddingBottom')) + 'px';        
                            };
                            
                            return val;
                    } : function (name) {
                                    return getComputedStyle(elem, null)[name];
                    },
                    minHeight = parseFloat(getStyle('height'));
            
            
            elem.style.resize = 'none';
            
            var change = function () {
                    var scrollTop, height,
                            padding = 0,
                            style = elem.style;
                    
                    if (elem._length === elem.value.length) return;
                    elem._length = elem.value.length;
                    
                    if (!isFirefox && !isOpera) {
                            padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
                    };
                    scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
                    
                    elem.style.height = minHeight + 'px';
                    if (elem.scrollHeight > minHeight) {
                            if (maxHeight && elem.scrollHeight > maxHeight) {
                                    height = maxHeight - padding;
                                    style.overflowY = 'auto';
                            } else {
                                    height = elem.scrollHeight - padding;
                                    style.overflowY = 'hidden';
                            };
                            style.height = height + extra + 'px';
                            scrollTop += parseInt(style.height) - elem.currHeight;
                            document.body.scrollTop = scrollTop;
                            document.documentElement.scrollTop = scrollTop;
                            elem.currHeight = parseInt(style.height);
                    };
                    changeTextArea();
                    wordinx = getPositionForTextArea(document.getElementById('message'));
            };
            
            addEvent('propertychange', change);
            addEvent('input', change);
            addEvent('focus', change);
            change();
    };
  	//多行文本框 
    function getPositionForTextArea(ctrl) {
        var CaretPos = 0;
        if (document.selection) { // IE Support 
            ctrl.focus();
            var Sel = document.selection.createRange();
            var Sel2 = Sel.duplicate();
            Sel2.moveToElementText(ctrl);
            var CaretPos = -1;
            while (Sel2.inRange(Sel)) {
                Sel2.moveStart('character');
                CaretPos++;
            }
        } else if (ctrl.selectionStart || ctrl.selectionStart == '0') { // Firefox support 
            CaretPos = ctrl.selectionStart;
        }
        return (CaretPos);
    }
    
	function openFaceDialog(){
		$("#ukefu-suggest").empty().hide();
		if(document.getElementById("faceindex").style.display == "none"){
			document.getElementById("faceindex").style.display= "block";
			document.getElementById("bottom").style.height = $('#message').height()+ 20 + document.getElementById("faceindex").offsetHeight + "px" ;
			document.getElementById("above").style.height = "calc(100% - "+($('#bottom').height())+"px)"
		}else{
			closeFaceDialog();
		}
		return false ;
	}	
	
	function closeFaceDialog(){
		document.getElementById("faceindex").style.display= "none";
		document.getElementById("bottom").style.height = $('#message').height() + "px" ;
		document.getElementById("above").style.height = "calc(100% - "+($('#message').height() + 20)+"px)" ;
	}
	
	function changeTextArea(){
		if(document.getElementById("faceindex").style.display == "none"){
			$('#bottom').height(document.getElementById('message').scrollHeight);
			document.getElementById("above").style.height = "calc(100% - "+(document.getElementById('message').scrollHeight+20)+"px)"
		}else{
			$('#bottom').height(document.getElementById('message').scrollHeight+document.getElementById("faceindex").offsetHeight);
			document.getElementById("above").style.height = "calc(100% - "+(document.getElementById('bottom').scrollHeight)+"px)"
		}
	}
	function insertImg(obj){
		if(wordinx >= 0){
			var text = $('#message').val();
			var value = text.substring(0 , wordinx) + "["+obj+"]" + text.substring(wordinx , text.length);
			$('#message').val(value);
			wordinx = wordinx + 2 + obj.length ;
		}
	}
	$(document).ready(function(){
		$(document).on("click" , '[data-toggle="suggest"]' , function(e){
			$('#message').val($(this).data("content"));
			sendMessage();	
		});
		$(document).on("click" , '[data-toggle="change"]' , function(e){
			var blocks = $('.ukefu-suggest-block') ;
			for(var i=0 ; i<blocks.length ; i++){
				if($(blocks[i]).is(":hidden") == false){
					$(blocks[i]).hide();
					if(i + 1 < blocks.length){
						$(blocks[i]).next().show();
					}else{
						$(blocks[0]).show();
					}
					break ;
				}
			}
		});
		window.addEventListener('resize', function () {
		     if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') {
		        window.setTimeout(function () {
		          document.activeElement.scrollIntoViewIfNeeded()
		        }, 0)
		      }
		});
		// 在输入框获取焦点, 键盘弹起后, 真的是一行代码
		var interval = setInterval(function() {
		    document.body.scrollTop = document.body.scrollHeight
		}, 100)

		$(document).on('submit.form.data-api','[data-toggle="ajax-form"]', function ( e ) {
			var formValue = $(e.target) ;
			$(this).ajaxSubmit({	  
				url:formValue.attr("action"),
				success: function(data){
					
				},
				error:function(xhr, type, s){  				
					//notification("",false);	//结束
				}
			}); 
			return false;
		});
	});
  </script>
    <!-- kindeditor -->
</head>
<body class="ukefu-im-theme" style="overflow:hidden;height:calc(100% - 50px);overflow-y: atuo;/* 或者scroll */-webkit-overflow-scrolling: touch;/* 解决ios滑动不流畅问题 */" class="ukefu-point-text">
	<div id="header" class="theme${inviteData.consult_dialog_color!''}">
		<img
			src="<#if inviteData?? && inviteData.consult_dialog_logo??>/res/image.html?id=${inviteData.consult_dialog_logo?url}<#else>/images/logo.png</#if>"
			style="height:50px;padding:10px;">
		
		<div class="ukefu-func-tab">
		   		<ul>
		   			<#if models?? && models["xiaoe"]?? && models["xiaoe"] == true>
		   				<li class="cur"><a href="javascript:void(0)"><#if inviteData?? && inviteData.aitabtitle??>${inviteData.aitabtitle}<#else>智能客服</#if></a></li>
		   				<#if inviteData.hideagent == false>
		   				<li><a href="/im/index.html?appid=${appid!''}&orgi=${orgi!''}<#if aiid??>&aiid=${aiid}</#if>&ai=false<#if client??>&client=${client!''}</#if><#if type??>&type=text</#if><#if skill??>&skill=${skill!''}</#if><#if agent??>&agent=${agent!''}</#if>&userid=${userid!''}&sessionid=${sessionid!''}<#if contacts?? && contacts.name??>&name=${contacts.name}</#if><#if contacts?? && contacts.phone??>&phone=${contacts.phone}</#if><#if contacts?? && contacts.email??>&email=${contacts.email}</#if><#if contacts?? && contacts.memo??>&memo=${contacts.memo}</#if>&t=${.now?long}"><#if inviteData?? && inviteData.agenttabtitle??>${inviteData.agenttabtitle}<#else>人工坐席</#if></a></li>
		   				</#if>
		   			<#else>
		   				<li class="cur"><a href="javascript:void(0)"><#if inviteData?? && inviteData.agenttabtitle??>${inviteData.agenttabtitle}<#else>人工坐席</#if></a></li>
		   			</#if>
		   		</ul>
	   		</div>
	</div>
	<div class="chat-above" id="above" style="height:calc(100% - 110px);">
		<div class="clearfix message  welcome">
			<span id="welcome-message"><#if inviteData.aimsg?? &&
				inviteData.aimsg!=''>${inviteData.aimsg?no_esc}<#else>${(inviteData.dialog_message!'欢迎您来咨询！')?no_esc}</#if>
				<#if topicList??>
				<ul class="info-list">
		        <#list topicList as topic>
		        	<#assign title = topic.title?replace('\\\"' , '')?replace('"' , '')?replace('\\/' , '/') >
					<li class="ukefu-suggest-item"><a href="javascript:void(0)" class="suggestitem" onclick="sendMessageTextWithID('${title!''}' , '${topic.id!''}')">${topic.title!''}</a></li>
				</#list>
				</ul>
				</#if>
			</span>
		</div>
		<#if chatMessageList?? && chatMessageList.content??> 
			<#list chatMessageList.content?reverse as chatMessage> 
				<#if chatMessage.msgtype == "status" && chatMessage.message == "end">
					<div class="clearfix chat-block connect-end">
						<span class="connect-end-message">${chatMessage.updatetime?number_to_datetime}，用户“<#if chatMessage?? && chatMessage.username??>${chatMessage.username!''}</#if>”已经离开</span>
					</div>
				<#else>
					<#if chatMessage.userid?? && userid?? && chatMessage.calltype?? && chatMessage.calltype = "in">
						<div class="clearfix chat-block">
							<div class="chat-right">
								<img class="user-img" src="/im/img/user.png" alt="">
								<div class="chat-message">
									<label class="time">${chatMessage.createtime!''}</label> <label
										class="user">${chatMessage.username!''}</label>
								</div>
								<div class="chatting-right">
									<i class="arrow arrow${inviteData.consult_dialog_color!''}"></i>
									<div
										class="chat-content theme${inviteData.consult_dialog_color!''}"><#include
										"/apps/im/media/message.html"></div>
								</div>
							</div>
						</div>
					<#else>
						<div class="clearfix chat-block">
							<div class="chat-left">
								<img class="user-img"
									src="<#if inviteData?? && inviteData.aiicon??>/res/image.html?id=${inviteData.aiicon?url}<#elseif inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>"
									alt="">
								<div class="chat-message">
									<label class="user">${chatMessage.username!inviteData.ainame!'小E'}</label> <label
										class="time">${chatMessage.createtime!''}</label>
								</div>
								<div class="chatting-left">
									<i class="arrow"></i>
									<div class="chat-content"><#include
										"/apps/im/media/message.html"></div>
								</div>
							</div>
						</div>
					</#if>
				</#if> 
			</#list> 
		</#if>
		<div class="ukefu-suggest" id="ukefu-suggest"></div>
	</div>
	
	<div class="mobile-chat-bottom" id="bottom">
		<form id="imgForm" action="/im/image/upload.html?userid=${userid!''}<#if aiid??>&aiid=${aiid}</#if>&appid=${appid!''}&username=${username!''}&orgi=${orgi!''}" data-toggle="ajax-form"" enctype="multipart/form-data">
			<a href="javascript:;" class="imgFile" onclick="closeFaceDialog">
				<img src="/im/img/img.png" class="chat-type" style="width:32px;height:32px;">
				<input type="file" name="imgFile" id="imgFile" accept="image/*" onChange="$('#imgForm').submit();$(this).val('');">
			</a>
		</form>
		<textarea id="message" name="content" maxlength="<#if inviteData.maxwordsnum gt 0>${inviteData.maxwordsnum}<#else>300</#if>"></textarea>
		<div class="btn-push clearfix" class="tools">
			<img id="facedialog" onclick="return openFaceDialog()" src="/im/img/face.png" style="width:32px;height:32px;"></a>
			<a href="javascript:void(0)" onClick="sendMessage();return false;"><img src="/im/img/send.png" style="width:32px;height:32px;"></a>
		</div>
		
		<div id="faceindex" style="display:none;height:200px;position: absolute;bottom: 0px;width:100%;overflow-x:auto;">
			<table class="ke-table" cellpadding="0" cellspacing="0" border="0" style="min-width:100%;">
				<tbody>
					<#list 0..4 as row>
					<tr>
						<#list 0..20 as col>
						<td class="ke-cell"><span class="ke-img"><img
								src="/im/js/kindeditor/plugins/emoticons/images/${row*20 + col}.png"
								border="0" alt="" onClick="insertImg('${row*20 + col}')"></span></td>
						</#list>
					</tr>
					</#list>
				</tbody>
			</table>
		</div>
	</div>
</div>
<#if (sessionConfig?? && sessionConfig.satisfaction?? && sessionConfig.satisfaction) || (snsaccount?? && snsaccount.satisfaction?? && snsaccount.satisfaction)>
<!--调查问卷弹框-->
<div class="diaShade" id="diaShade" style="display: none"></div>
<div class="dialogWrap" id="dialogWrap" style="display: none;width:auto;height:auto;margin-left:0px;left:0px;">
    <div class="dialogCon">
        <form id="commentContent" onSubmit="return submitForm(this)">
        	<input type="hidden" name="id" id="agentserviceid" name="agentserviceid">
            <h2 class="diaHeader clearfix">
                <span>评价</span>
                <hr>
            </h2>
            <p class="title">您是否对此次服务满意?</p>
            <!--评价-->
           <p style="margin-top:20px;">
                <span style="float:left;">评价：</span>
                <span style="position: relative;top: 0px;left: 13px;">
                <#assign defaultvalue = "">
                <#if commentList??>
                <#list commentList as comment>
                <div style="margin-left:55px;margin-bottom:20px;">
		            <input type="radio" name="satislevel" value="${comment.code!''}" <#if comment_index == 0>checked="checked"</#if> id="dic_${comment.id!''}" onclick="document.getElementById('satislevel_input').value = this.value">
		            <label for="dic_${comment.id!''}" class="radio">${comment.name!''}</label>
		        </div>
                <#if defaultvalue == "">
                <#assign defaultvalue = comment.code>
                </#if>
                </#list>
                </#if>
                <input type="hidden" id="satislevel_input" name="t" value="${defaultvalue}">
                </span>
            </p>
            <!--按钮-->
            <p class="submitBtnWrap" style="text-align:center;">
				<input type="submit" class="btn submitBtn" id="submitBtn" value="提 交">
            </p>
        </form>
    </div>
</div>
</#if>
<script>
	var service_end = false;
	// 调查问卷
	var diaShade = document.getElementById('diaShade');
	var dialogWrap = document.getElementById('dialogWrap');
	function popup(para) {
		diaShade.style.display = para;
		dialogWrap.style.display = para;
	}
	document.getElementById('above').scrollTop = document
			.getElementById('above').scrollHeight; //滚动到 对话内容的 底部
	// 参数连接
	var timer = setInterval(function(){
			if(socket!=null && socket.connected == true){
				socket.emit("ping");
			}
		},5000);
	var hostname = location.hostname;
	var socket = null;
    var webimWoker = {
    		init:function(url){
    			socket = io.connect(url , options);
					socket.on('connect', function() {
						//service.sendRequestMessage(); 
						//output('<span id="connect-message">'+ new Date().format("yyyy-MM-dd hh:mm:ss") + ' 开始沟通' +'</span>' , 'message connect-message');
						socket.emit('new', {
							<#if contacts?? && contacts.name??>
							name : "${contacts.name!''}",
							phone:"${contacts.phone!''}",
							email:"${contacts.email}",
							memo:"${contacts.memo!''}",
							nickname:"${contacts.name}",
							<#else>
				    		nickname:"${username}",
							</#if>
							orgi:"${inviteData.orgi!''}",
							appid : "${appid!''}",
							aiid : "${aiid!''}",
							user:"${creater!''}",
							session:"${sessionid!''}",
							mobile:"${mobile!'0'}",
							osname:"${(osname!'')?url}",
							browser:"${(browser!'')?url}"
							<#if skill??>,skill:"${skill}"</#if>
							<#if agent??>,agent:"${agent}"</#if>
							<#if title??>,title:"${title?url}"</#if>
							<#if traceid??>,url:"${url?url}"</#if>
							<#if traceid??>,traceid:"${traceid}"</#if>
						});
						service_end = false ;
	    		        fineshed = false ;
					})
					socket
							.on(
									"agentstatus",
									function(data) {
										var message = "${inviteData.aisuccesstip!''}";
										if (message != "" && agent == false) {
											document.getElementById('connect-message').innerHTML = message;
										} else {
											document.getElementById('connect-message').innerHTML = data.message;
										}
									})
					socket.on("status", function(data) {
						var message = "${inviteData.aisuccesstip!''}";
						if (message == "" || agent == true) {
							message = data.message;
						}
						if(data.message!=""){
							output('<span id="connect-message"  <#if inviteData.tipmsgbgcolor?? && inviteData.tipmsgbgcolor!=''>class="theme${inviteData.tipmsgbgcolor!''}"</#if>>' + message + '</span>', 'message connect-message');
						}
						if (data.messageType == "end") {
							service_end = true;
						}
						<#if (sessionConfig?? && sessionConfig.satisfaction?? && sessionConfig.satisfaction) || (snsaccount?? && snsaccount.satisfaction?? && snsaccount.satisfaction)>
						if(data.messageType == "invit"){
							<#if (sessionConfig?? && sessionConfig.satisfaction?? && sessionConfig.satisfaction) || (snsaccount?? && snsaccount.satisfaction?? && snsaccount.satisfaction)>
							if(invite == false){
								document.getElementById("diaShade").style.display = "block" ;
								document.getElementById("dialogWrap").style.display = "block" ;
								invite = true ;
							}
							</#if>
						}
						</#if>
						if(document.getElementById("agentserviceid")){
							document.getElementById("agentserviceid").value = data.agentserviceid ;
						}
					});
					var insuggest = false;
					$('#message').on("input propertychange",function(){
				    	var value = $(this).val();
				    	if(value.trim()!='' && insuggest == false){
				    		insuggest = true ;
				    		$.ajax({
				    			url: "/im/suggest/mobile/${appid!''}.html?userid=${userid!''}&skill=${skill!''}&aiid=${inviteData.aiid!''}&q="+encodeURIComponent(value),
				    			success:function(data){
				    				if(data.trim() != ''){
				    					$("#ukefu-suggest").empty().html(data).show();
				    				}else{
				    					$("#ukefu-suggest").empty().hide();
				    				}
				    				insuggest = false ;
				    			}
				    		});
				    	}
				    });
					socket
							.on(
									'message',
									function(data) {
										var chat = document
												.getElementsByClassName('chatting-left').innerText;
										chat = data.message;
										if(data.quickagent == true){
					    		        	//转人工
					    					callback = "quickagent()";
					    					sendDisconnect();
					    		        }else{
											if (data.messageType == "image") {
												chat = "<img src='"+data.message+"' class='ukefu-media-image'>";
											}else if(data.messageType == "voice"){
									        	chat = template($('#message_tpl').html(), {data: data}) ;
									        }else if(data.messageType == "file"){
									        	chat = "<div class='ukefu-message-file'><div class='ukefu-file-icon'><img src='/im/img/file.png'></div><div class='ukefu-file-desc'><a href='"+data.message+"' target='_blank'><div>"+data.filename+"</div><div>"+(data.filesize/1024).toFixed(3)+"Kb</div></a></div></div>" ;
									        }
											var text = '<ul class="info-list">' ;
											if(data.suggest!=null){
											 	for(inx =0 ; inx < data.suggest.length ; inx++){
											 		var item = data.suggest[inx] ;
											 		text = text + '<li class="ukefu-suggest-item"><a href="javascript:void(0)" class="suggestitem" onclick="sendMessageTextWithID(\''+item.title.replace(/'/g,"")+'\' , \''+item.id+'\')">'+item.title+'</a></li>' ;
											 	}
											 	text = text + "</ul>";
											 	chat = chat + text ;
											}
											if (data.calltype == "in") {
												output(
														'<div class="chat-right"> <img class="user-img" src="/im/img/user.png" alt=""><div class="chat-message"><label class="time">'
																+ data.createtime
																+ '</label><label  class="user">'
																+ data.nickName
																+ '</label> </div><div class="chatting-right"><i class="arrow arrow${inviteData.consult_dialog_color!''}"></i><div class="chat-content theme${inviteData.consult_dialog_color!''}">'
																+ chat + '</div></div>',
														"chat-block");
											} else if (data.calltype == "out") {
												/***延迟1秒执行，不然太快****/
												/*var ext_message = "" ;
					    						//开启知识点评价功能
					    						<#if aiConfig?? && aiConfig.topicuseful>
					    						if(data.topic == true){
					    							ext_message = "<div class='ukefu-ai-tip' id='ukefu_ai_msg_"+data.id+"'><span><#if aiConfig.topicusefulmsg?? && aiConfig.topicusefulmsg!=''>${aiConfig.topicusefulmsg!''}<#else>此条知识是否解决了问题？</#if></span><span><span class='ukefu-ai-btn ukefu-ai-btn-ok' data-id='"+data.id+"'><i class='iconfont'>&#xe640;</i>&nbsp;&nbsp;<#if aiConfig.topicusefulok?? && aiConfig.topicusefulok!=''>${aiConfig.topicusefulok}<#else>已解决</#if></span><span class='ukefu-ai-btn ukefu-ai-btn-no'  data-id='"+data.id+"'><i class='iconfont'>&#xe629;</i>&nbsp;&nbsp;<#if aiConfig.topicusefulno?? && aiConfig.topicusefulno!=''>${aiConfig.topicusefulno}<#else>未解决</#if></span></span></div>" ;
					    						}
					    						</#if>
												setTimeout(
														function() {
															output(
																	'<div class="chat-left"> <img class="user-img" src="<#if inviteData?? && inviteData.aiicon??>/res/image.html?id=${inviteData.aiicon?url}<#elseif inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt=""><div class="chat-message"><label  class="user">${inviteData.ainame!'小E'}</label><label class="time">'
																			+ data.createtime
																			+ '</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content">'
																			+ chat + ext_message + '</div></div>',
																	"chat-block");
														}, 500);*/
												setTimeout(function(){
													var ext_message = "" ;
													//开启知识点评价功能
													<#if aiConfig?? && aiConfig.topicuseful>
														if(data.topic == true){
															ext_message = "<div class='ukefu-ai-tip' id='ukefu_ai_msg_"+data.id+"'><span><#if aiConfig.topicusefulmsg?? && aiConfig.topicusefulmsg!=''>${aiConfig.topicusefulmsg!''}<#else>此条知识是否解决了问题？</#if></span><span><span class='ukefu-ai-btn ukefu-ai-btn-ok' data-id='"+data.id+"'><i class='iconfont'>&#xe640;</i>&nbsp;&nbsp;<#if aiConfig.topicusefulok?? && aiConfig.topicusefulok!=''>${aiConfig.topicusefulok}<#else>已解决</#if></span><span class='ukefu-ai-btn ukefu-ai-btn-no'  data-id='"+data.id+"'><i class='iconfont'>&#xe629;</i>&nbsp;&nbsp;<#if aiConfig.topicusefulno?? && aiConfig.topicusefulno!=''>${aiConfig.topicusefulno}<#else>未解决</#if></span></span></div>" ;
														}
													</#if>
													<#if aiConfig?? && aiConfig.sysmsgtransagent>
														if(data.topic == false && data.matchtype == "no"){
															ext_message = "<div class='ukefu-ai-tip' id='ukefu_ai_msg_"+data.id+"'><span class='ukefu-ai-btn-sysmsgtrans'><#if aiConfig.sysmsgtransagentmsg?? && aiConfig.sysmsgtransagentmsg!=''>${aiConfig.sysmsgtransagentmsg!''}</#if></span><#if aiConfig?? && aiConfig.quickagent?? && aiConfig.quickagent == true><span class='ukefu-ai-btn ukefu-ai-quickagent'><i class='iconfont'>&#xe698;</i>&nbsp;&nbsp;${aiConfig.quickagentmsg!'立即转人工坐席'}</span></#if></span></div>" ;
														}
													</#if>


													if(data.staticagent == true && <#if inviteData?? && inviteData.staticagent == true>true<#else>false</#if>){
														//转人工
														staticagent = true ;
														callback = "quickagent(true)";
														sendDisconnect(true);
													}else{
														output('<div class="chat-left"> <img class="user-img" src="<#if inviteData?? && inviteData.aiicon??>/res/image.html?id=${inviteData.aiicon?url}<#elseif inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt=""><div class="chat-message"><label  class="user">'+(data.nickName != null && data.nickName != "" ? data.nickName : "${inviteData.ainame!'小E'}")+'</label><label class="time">'+data.createtime+'</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content">'+chat + ext_message+'</div></div>' , "chat-block");
													}
												} , 500);
											}
					    		        }
									});
				
					socket.on('disconnect', function() {
						output('<span id="connect-message" <#if inviteData.tipmsgbgcolor?? && inviteData.tipmsgbgcolor!=''>class="theme${inviteData.tipmsgbgcolor!''}"</#if>>连接服务失败，智能在线咨询服务不可用</span>',
								'message connect-message');
						$('.ukefu-ai-quickagent').remove();
			    		webimWoker.off();
			    		if(callback!=null){
	    		    		setTimeout(function(){eval(callback);callback = null ; }, 500);
	    		    	}
					});
    		},
    		off:function(){
    			webimWoker.delevent('connect');
    			webimWoker.delevent('agentstatus');
    			webimWoker.delevent('message');
    			webimWoker.delevent('disconnect');
    		},
    		delevent:function(name){
    			var event = socket.listeners(name) ;
    			if(event.length > 1){
    				for(i = 0 ; i<event.length ; i++){
	    				socket.off(name , event[i]);
    				}
    			}else{
    				socket.off(name , event[0]);
    			}
    		}
    }
	function sendDisconnect() {
    	if(socket!=null){
    		socket.emit('end', {
				orgi:"${inviteData.orgi!''}",
				appid : "${appid!''}",
				aiid : "${aiid!''}",
				user:"${creater!''}",
			});
			socket.disconnect();
		}
	}
	function sendMessage() {
		insuggest = false ;
		$("#ukefu-suggest").empty().hide();
		var count = document.getElementById('message').value.length;
		if (count > 0 && service_end == false) {
			var message = $("#message").val();
			sendMessageText(message);
			$("#message").val("") ;
			wordinx = 0 ;
		} else if (service_end == true) {
			alert("服务器已断开和您的对话");
		}
	}
	function sendMessageTextWithID(message , id) {
		if (message != "") {
			socket.emit('message', {
				appid : "${appid!''}",
				username : "${username!''}",
				channel : "webim",
				type : "message",
				contextid : "${sessionid!''}",
				orgi : "${orgi!''}",
				mediaid:id,
				message :  message
			});
		}
	}
	function sendMessageText(message){
    	if(message!= ""){ 
    		sendMessageTextWithID(message , null) ;
		}
    }
	function output(message, clazz) {
		if (clazz == "message connect-message") {
			var messages = document.getElementsByClassName("connect-message");
			for (inx = 0; inx < messages.length;) {
				document.getElementById('above').removeChild(messages[inx]);
				inx++;
			}
		}
		var element = ("<div class='clearfix "+clazz+"'>" + " " + message + "</div>");
		$('#above').append(element);
		document.getElementById('above').scrollTop = document
				.getElementById('above').scrollHeight;
	}
	function update(id, message) {
		document.getElementById(id).innerHTML = message;
	}
	autoTextarea(document.getElementById("message"));// 调用
	$('#message').click(function(){
		wordinx = getPositionForTextArea(document.getElementById('message'));
		closeFaceDialog();
	});
	var message = {
	// text:data.message,
	// picture:function(){

	// }
	// file:function(){

	// }
	// lang:function(){

	// }
	// goods:function(){

	// }
	// POI:function(){

	// }

	}
	$(document).ready(function(){
		$(document).on('click','.ukefu-ai-btn-ok', function ( e ) {
			var obj = $(this) ;
			$('#ukefu_ai_msg_'+$(this).data("id")).empty().html("<span class='ukefu-ai-btn-ok-tip'><i class='iconfont'>&#xe61b;</i>&nbsp;&nbsp;${aiConfig.topicusefultip!''}</span>") ;
			$.ajax({
	             type: "GET",
	             url: "/rest/webim/message/useful.json?id="+$(obj).data("id"),
	             dataType: "json",
	             success: function(data){
	             	
	             }
	         });
		});
		$(document).on('click','.ukefu-ai-btn-no', function ( e ) {
			var obj = $(this) ;
			$.ajax({
	             type: "GET",
	             url: "/rest/webim/message/unuseful.json?id="+$(obj).data("id"),
	             dataType: "json",
	             success: function(data){
	             	
	             }
	         });
			$.ajax({
	             type: "GET",
	             url: "/rest/webim/agent.json?orgi=${orgi}",
	             dataType: "json",
	             success: function(data){
	             	if(data.data.agents > 0){
	             		$('#ukefu_ai_msg_'+$(obj).data("id")).empty().html("<span class='ukefu-ai-btn-no-tip'><i class='iconfont'>&#xe62d;</i>&nbsp;&nbsp;${aiConfig.topicusefultip!''}</span><#if aiConfig?? && aiConfig.quickagent?? && aiConfig.quickagent == true><span class='ukefu-ai-btn ukefu-ai-quickagent'><i class='iconfont'>&#xe698;</i>&nbsp;&nbsp;${aiConfig.quickagentmsg!'立即转人工坐席'}</span></#if>") ;	             		
	             	}else{
	             		$('#ukefu_ai_msg_'+$(obj).data("id")).empty().html("<span class='ukefu-ai-btn-no-tip'><i class='iconfont'>&#xe62d;</i>&nbsp;&nbsp;${aiConfig.topicusefultip!''}</span><span><#if aiConfig?? && aiConfig.noagentmsg?? && aiConfig.noagentmsg != ''>${aiConfig.noagentmsg}<#else>无人工坐席在线</#if></span>") ;
	             	}
	             }
	         });
			
		});
		$(document).on('click','.ukefu-ai-quickagent', function ( e ) {
			//转人工
			callback = "quickagent()";
			sendDisconnect();
		});
		webimWoker.init('${schema!'http'}://'
				+ hostname
				+ ':${port}/im/ai');
		
		document.addEventListener('visibilitychange', function() {
			setTimeout(function(){
				if(document.hidden == false) {
					if((socket!=null && socket.connected) == false){
						webimWoker.off();
						if(agent == true){
							quickagent();
						}else{
							webimWoker.init('${schema!'http'}://'
								+ hostname
								+ ':${port}/im/ai');
						}
					}					
				}
			},2000);
		}) ;
	});
	function submitForm(form){
		$.post("/im/satis.html?orgi=${orgi!''}&"+"id="+form.id.value+"&satislevel="+document.getElementById("satislevel_input").value, function(data) {
			document.getElementById("diaShade").style.display = "none" ;
			document.getElementById("dialogWrap").style.display = "none" ;
			alert("服务评价已提及，请关闭浏览器！");
		});
		return false ;
	}
	
	function quickagent(){
		webimWoker.init('${schema!'http'}://'+hostname+':${port}/im/user') ;
		agent = true ;
		callback = null ;
	}
	<#if inviteData?? && inviteData.enablevoice?? && inviteData.enablevoice == true>
	UCKeFuVoice.init("mobile");
	</#if>
</script>
<script id="message_tpl" type="text/html">
	<p class="weixinAudio" id="voice_media_<%:=data.id%>" style="<% if(data.duration > 30) {%>width:300px;<% }else{ %>width:<%:=50+data.duration* 10%>px;<%}%>">
		<audio src="<%:=data.message%>" id="media" width="1" height="1" preload></audio>
		<span id="audio_area" class="db audio_area">
			<span class="audio_wrp db">
				<span class="audio_play_area">
					<i class="icon_audio_default"></i>
					<i class="icon_audio_playing"></i>
				</span>
				<span class="audio_length tips_global"><%:=data.duration %>秒</span>
				<span id="audio_progress" class="progress_bar" style="width: 0%;"></span>
			</span>
		</span>
	</p>
	<script type='text/javascript'>
		$('#voice_media_<%:=data.id%>').weixinAudio({
			autoplay:false
		});
	<\/script>
</script>
</body>
</html>